package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.base.query.QueryObject;
import cn.wolfcode.car.common.config.SystemConfig;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {
    @Resource
    private BpmnInfoMapper bpmnInfoMapper;
    @Resource
    private RepositoryService repositoryService;

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectOne(id);
    }

    @Override
    public TablePageInfo<BpmnInfo> query(QueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(bpmnInfoMapper.queryForList(qo));
    }

    @Override
    public void save(String uploadPath, BpmnInfo bpmnInfo) throws Exception {
        FileInputStream stream = new FileInputStream(new File(SystemConfig.getProfile(), uploadPath));
        Deployment deploy;
        ProcessDefinition processDefinition;
        // 根据 Activiti 生成流程定义对象
        if (uploadPath.endsWith("zip")) {
            // 将 bpmn 文件部署 Activiti 中
            deploy = repositoryService.createDeployment()
                    .addZipInputStream(new ZipInputStream(stream))
                    .deploy();
        } else {
            // 将 bpmn 文件部署 Activiti 中
            deploy = repositoryService.createDeployment()
                    .addInputStream(uploadPath, stream)
                    .deploy();
        }
        processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        // 封装成 bpmnInfo 对象, 保存
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
        stream.close();
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.update(bpmnInfo);
    }

    @Override
    public InputStream readResource(String deploymentId, String type) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if ("xml".equalsIgnoreCase(type)) {
            return repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        } else {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            return new DefaultProcessDiagramGenerator()
                    .generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        }
    }

    @Override
    public void deleteById(Long id) {
        BpmnInfo bpmnInfo = this.get(id);
        bpmnInfoMapper.deleteById(id);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        boolean b = file.exists() && file.delete();
    }

    @Override
    public BpmnInfo queryType(String type) {
        return bpmnInfoMapper.queryType(type);
    }
}
